﻿using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Update.Utils.Interfaces;

namespace Update.Utils.Net
{
    /// <summary>
    /// 网络操作辅助类
    /// </summary>
    public class NetworkHelper : INetworkHelper
    {
        private readonly HttpClient _httpClient;

        /// <summary>
        /// 创建网络帮助类实例
        /// </summary>
        public NetworkHelper()
        {
            // 配置HttpClient
            var handler = new HttpClientHandler
            {
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                AllowAutoRedirect = true,
                MaxAutomaticRedirections = 10
            };

            _httpClient = new HttpClient(handler)
            {
                Timeout = TimeSpan.FromMinutes(10) // 较长的超时时间用于大文件下载
            };

            // 设置通用的User-Agent
            _httpClient.DefaultRequestHeaders.Add("User-Agent", "AppUpdater/1.0");
        }

        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url">下载地址</param>
        /// <param name="localPath">本地保存路径</param>
        /// <param name="progressCallback">进度回调</param>
        /// <returns>是否成功</returns>
        public async Task<bool> DownloadFileAsync(string url, string localPath, Action<long, long> progressCallback = null)
        {
            try
            {
                // 确保目录存在
                string directory = Path.GetDirectoryName(localPath);
                if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // 使用流式下载以支持进度报告
                using (var response = await _httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
                {
                    response.EnsureSuccessStatusCode();
                    
                    var totalBytes = response.Content.Headers.ContentLength ?? -1L;
                    var downloadedBytes = 0L;
                    var buffer = new byte[8192];
                    
                    using (var contentStream = await response.Content.ReadAsStreamAsync())
                    using (var fileStream = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.None, buffer.Length, true))
                    {
                        int bytesRead;
                        while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                        {
                            await fileStream.WriteAsync(buffer, 0, bytesRead);
                            
                            downloadedBytes += bytesRead;
                            progressCallback?.Invoke(downloadedBytes, totalBytes);
                        }
                    }
                }
                
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 发送GET请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应内容</returns>
        public async Task<string> HttpGetAsync(string url, WebHeaderCollection headers = null)
        {
            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                {
                    // 添加自定义头
                    if (headers != null)
                    {
                        foreach (string key in headers.AllKeys)
                        {
                            request.Headers.Add(key, headers[key]);
                        }
                    }

                    using (var response = await _httpClient.SendAsync(request))
                    {
                        response.EnsureSuccessStatusCode();
                        return await response.Content.ReadAsStringAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"HTTP GET请求失败: {ex.Message}", ex);
            }
        }

        /// <summary>
        /// 发送POST请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">POST数据</param>
        /// <param name="contentType">内容类型</param>
        /// <param name="headers">请求头</param>
        /// <returns>响应内容</returns>
        public async Task<string> HttpPostAsync(string url, string data, string contentType = "application/json", WebHeaderCollection headers = null)
        {
            try
            {
                using (var request = new HttpRequestMessage(HttpMethod.Post, url))
                {
                    // 添加自定义头
                    if (headers != null)
                    {
                        foreach (string key in headers.AllKeys)
                        {
                            request.Headers.Add(key, headers[key]);
                        }
                    }

                    request.Content = new StringContent(data, Encoding.UTF8, contentType);

                    using (var response = await _httpClient.SendAsync(request))
                    {
                        response.EnsureSuccessStatusCode();
                        return await response.Content.ReadAsStringAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"HTTP POST请求失败: {ex.Message}", ex);
            }
        }


    }
} 